package com.sf.web.controller;

import com.sf.domain.Department;
import com.sf.domain.Employee;
import com.sf.qo.EmployeeQueryObject;
import com.sf.service.IDepartmentService;
import com.sf.service.IEmployeeService;
import com.sf.util.PageResult;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController  {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;


    /**
     * 接受 /employee/list
     */
    @RequestMapping("/list")
    public String list(Model model,@ModelAttribute("qo") EmployeeQueryObject queryObject){
        PageResult result = employeeService.query(queryObject);
        model.addAttribute("pageResult",result);
        model.addAttribute("departments",departmentService.listAll());
        return "employee/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        // 表现层去调用业务层实现
        employeeService.delete(id);
        return "redirect:/employee/list";
    }


    /**
     * 接受
     * /employee/input
     * 注意判断id 是否为空
     *
     */
    @RequestMapping("/input")
    public String input(Model model,Long id){
        if(id != null){
            // 根据id 查询数据库信息, 放到model 当中
           Employee employee= employeeService.get(id);
           model.addAttribute("employee",employee);
        }
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments",departments);
        // 跳转到编辑界面
        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee){
        employeeService.saveOrUpdate(employee);
        return "redirect:/employee/list";
    }
}
